<template>
	<div>
		<el-container>
			<head-top></head-top>
			<el-header>
				<el-form :inline="true" :model="formInline" @submit.native.prevent class="form-inline form-menu-list">
					<el-form-item label="合同名称">
						<el-input v-model="formInline.contractName" placeholder="" @keyup.enter.native="onSearch"></el-input>
					</el-form-item>
					<el-form-item label="开始时间">
						<el-date-picker v-model="formInline.contractStartdate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="结束时间">
						<el-date-picker v-model="formInline.contractEnddate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="onSearch">查询</el-button>
					</el-form-item>
				</el-form>
				<el-form :inline="true" class="form-inline form-menu-function">
					<el-button type="primary" icon="el-icon-edit" @click="create">新增</el-button>
				</el-form>
			</el-header>
			<el-main>
				<el-table :data="tableData" :row-class-name="tableRowClassName" show-summary :summary-method="getSummaries" border>
					<el-table-column prop="id" label="序号" width="100">
					</el-table-column>
					<el-table-column prop="contractName" label="合同名称" width="200">

					</el-table-column>
					<el-table-column prop="contractPrice" label="合同费用(元)" width="150">

					</el-table-column>
					<el-table-column prop="contractContent" label="合同详情" width="300">

					</el-table-column>
					<el-table-column prop="contractStartdate" label="生效时间" width="200">
					</el-table-column>
					<!-- <el-table-column prop="status" label="状态" width="300"> -->
					<el-table-column prop="contractEnddate" label="到期时间" width="200">

					</el-table-column>
					<el-table-column prop="status" label="合同状态" width="100" :formatter="formatterstatus">

					</el-table-column>
					<el-table-column label="操 作" width="400">
						<template slot-scope="scope">
							<el-button size="medium" type="info" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
							<el-button size="medium" type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
							<el-switch v-model="scope.row.alert" active-text="过期告警" inactive-text="取消告警" inactive-value="2" active-value="1" @change="switchChange(scope.row)">
							</el-switch>
						</template>
					</el-table-column>
				</el-table>
				<div class="block">
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
					 :page-sizes="[10, 30, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count">
					</el-pagination>
				</div>
			</el-main>
			<el-dialog :title="title" :visible.sync="dialogFormVisible">
				<el-form :model="dialogform" :rules="rules2" ref="dialogform">
					<el-form-item label="合同名称" :label-width="formLabelWidth">
						<el-input v-model="dialogform.contractName" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="合同费用(元)" :label-width="formLabelWidth" prop="">
						<el-input v-model="dialogform.contractPrice" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="合同详情" :label-width="formLabelWidth">
						<el-input type="textarea" :rows="5" v-model="dialogform.contractContent" autocomplete="off"></el-input>
						 
					</el-form-item>
					<el-form-item label="生效时间" :label-width="formLabelWidth">
						<el-date-picker v-model="dialogform.contractStartdate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="到期时间" :label-width="formLabelWidth">
						<el-date-picker v-model="dialogform.contractEnddate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="合同状态" :label-width="formLabelWidth">
						<el-select v-model="dialogform.status" placeholder="请选择">
							<el-option key="1" value="1" label="生效">
							</el-option>
							<el-option key="2" value="2" label="失效">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="备注" :label-width="formLabelWidth">
						<el-input v-model="dialogform.description" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item>
						<!-- 	<el-upload  style="margin-bottom: 0px;" ref="upload" action="/api/upload/part" 
						 :file-list="fileList">
							<el-button slot="trigger" size="small" type="primary" style="margin-bottom: 0px;" >选取文件</el-button>
						</el-upload> -->
						<el-upload style="margin-top: 0px;" ref="upload" :action="actionurl" with-credentials="true" :file-list="fileList" multiple :limit="5"
						 :on-change="handleChange" :on-success="handleSuccess" :show-file-list=false>
							<el-button slot="trigger" size="small" type="primary" style="margin-bottom: 0px;">选取文件</el-button>
						</el-upload>
						<el-upload style="margin-top: 0px;" :action="actionurl" :on-preview="handlePreview" :on-remove="handleRemove"
						 :file-list="dialogform.cmdbUploadList" :before-remove="beforeRemove">
						</el-upload>
					</el-form-item>


				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取 消</el-button>
					<el-button type="primary" @click="dialogFormsubmit('dialogform')">确 定</el-button>
				</div>
			</el-dialog>
		</el-container>
	</div>
</template>

<script>
	import headTop from '@/components/headTop'
	import {
		mapGetters
	} from 'vuex';

	import {
		update,
		list,
		del,
		search
	} from '@/api/contract'
	import {
		downLoadMix
	} from '@/api/download'

	export default {
		data() {
			return {
				formLabelWidth: "20",
				formInline: {

				},
				dialogform: {
					status: "",
					cmdbUploadList: []
				},
				dialogFormVisible: false,
				title: "合同编辑",
				tableData: [],
				count: 0,
				currentPage: 1,
				pageSize: 10,
				rules2: {

				},
				actionurl: "",
				activeNames: [],
				// cmdbUploadList: [],
				fileList: [],
				// activeNames: ['1','2','3','4','5'],
			}
		},
		created() {
			this.onSearch();
			this.actionurl = process.env.VUE_APP_BASE_API + "/upload/file?domain=" + process.env.VUE_APP_BASE_API

		},
		computed: {
			...mapGetters({
				contractstatusoptions: 'getContractStatusOptions',
			}),
		},
		methods: {
			handleSizeChange(val) {
				this.pageSize = val;
				this.onSearch();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.onSearch();
			},
			create() {
				this.dialogform = {
					status: "1",
					alert: "1",
					cmdbUploadList: []
				};
				this.dialogFormVisible = true;
			},
			onSearch() {
				search(this.formInline, this.pageSize, this.currentPage)
					.then((response) => {

						this.inittable(response)
					})
			},
			tableRowClassName({
				row,
				rowIndex
			}) {
				if (row.status == 1) {
					return 'warning-row';
				} else if (row.status == 0) {
					return 'success-row';
				}
				return '';
			},
			handleEdit(index, row) {
				console.dir(row)
				// this.fileList = []
				this.dialogform = JSON.parse(JSON.stringify(row));
				// this.fileList = this.dialogform.cmdbUploadList
				this.dialogFormVisible = true

			},
			async handleDelete(index, row) {
				this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					del(row)
						.then((response => {
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
							this.onSearch()
						}))
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});

			},
			inittable(response) {
				this.tableData = response.items;
				this.tableData.forEach((data) => {
					data.contractStartdate = this.timestampToTime(data.contractStartdate)
					data.contractEnddate = this.timestampToTime(data.contractEnddate)
					// if(data.cmdbUploadList){
					// 	data.cmdbUploadList.forEach((data)=>{
					// 		data.status = "success"
					// 	})
					// }
				})
				this.count = response.totalNum;
			},
			dialogFormsubmit(formName) {
				console.dir(this.$refs[formName])
				this.$refs[formName].validate((valid) => {
					if (valid) {
						update(this.dialogform)
							.then((response) => {
								console.log("123123", this.fileList)
								this.dialogFormVisible = false;
								this.$message({
									type: 'success',
									message: '操作成功'
								});
								this.onSearch();
							})
					}
				})
			},
			addDeployItem() {
				console.log("this.dialogform.cmdbDeployList: " + this.dialogform.cmdbDeployList);
				this.dialogform.cmdbDeployList.push({
					deployName: '点我修改',
				})
			},
			deleteDeployItem(item, index) {
				this.dialogform.cmdbDeployList.splice(index, 1)
			},
			formatterdeployType(row, column, cellValue, index) {
				return this.deploytypeoptions[cellValue]
			},
			formatterdeployHostname(row, column, cellValue, index) {
				let hostname = '';
				if (cellValue) {
					let hostValue = cellValue.split(";")
					if (hostValue) {
						hostValue.forEach((item) => {
							hostname = hostname + item + "\n"
						})
					}

				}
				return hostname;
			},
			timestampToTime(timestamp) {
				if (timestamp) {
					var date = new Date(timestamp)
					var Y = date.getFullYear() + '-';
					var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
					var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
					return Y + M + D
				}

			},
			handleRemove(file, fileList) {
				console.log("file", file, "filelist", fileList);
				if (this.dialogform.cmdbUploadList) {
					this.dialogform.cmdbUploadList.forEach((item, index, arr) => {
						if (item.url == file.url) {
							this.dialogform.cmdbUploadList.splice(index, 1)
						}
					})
				}
				// fileList.forEach((data) => {
				// 	if(data.response){
				// 		this.dialogform.cmdbUploadList.push(data.response.data)
				// 	}
				// 	
				// })

			},
			handlePreview(file) {
				console.log(file)
				// this.$router.push({
				// 	path: file.url,
				// })
				// window.open("api/"+file.url)
				downLoadMix('', file.url, file.name)
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			handleChange(files, fileList) {
				console.log("fileList222222", fileList)
			},
			beforeRemove(file, fileList) {
				console.dir("fileList123", fileList)
				return this.$confirm(`确定移除 ${ file.name }？`)
			},
			submitUpload() {
				this.$refs.upload.submit()
				console.dir("response22222")


			},
			handleSuccess(response, file, fileList) {
				if (response.code == "200") {
					response.data.size = file.size
					this.dialogform.cmdbUploadList.push(response.data)

				}

			},
			handleProgress(event, file, fileLis) {

			},
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '总价';
						return;
					}
					if (column.property == 'contractPrice') {
						const values = data.map(item => Number(item[column.property]));
						if (!values.every(value => isNaN(value))) {
							sums[index] = values.reduce((prev, curr) => {
								const value = Number(curr);
								if (!isNaN(value)) {
									return prev + curr;
								} else {
									return prev;
								}
							}, 0);
							sums[index] += ' 元';
						} else {
							sums[index] = '';
						}
					}

				});

				return sums;
			},
			formatterstatus(row, column, cellValue, index) {
				return this.contractstatusoptions[cellValue]
			},
			switchChange(row){
				update(row)
			}



		},
		components: {
			headTop,
		},
	};
</script>

<style>
	.el-table .cell {
		white-space: pre-line !important;
	}

	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 120px;
		color: #99a9bf;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 30%;
	}

	.demo-table-expand el-input {
		width: 500px;
	}
</style>
